import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
//        初始化用户界面
        Map<String, String> userLofinInfo = initeUI();
//        验证用户名和密码
        boolean loginSucces = login(userLofinInfo);
//        输出结果
        System.out.println(loginSucces ? "登录成功" : "登录失败");
    }

    /*
     * 用户登录
     * @param userLoginInfo 用户登录信息
     * @return true表示成功，false表示失败
     * */
    private static boolean login(Map<String, String> userLofinInfo) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String loginName = userLofinInfo.get("loginName");
        String loginPwd = userLofinInfo.get("loginPwd");
        boolean loginSucces = false;
//        使用资源绑定器绑定属性配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String pwd = bundle.getString("pwd");
        try {
//            1.注册驱动
            Class.forName(driver);
//            2.获取连接
            conn = DriverManager.getConnection(url, user, pwd);
//            3.获取数据库操作对象
            stmt = conn.createStatement();
//            4.执行sql
            String sql = "select * from t_user where loginName = '" + loginName + "' and loginPwd = '" + loginPwd + "'";
            rs = stmt.executeQuery(sql);
            if (rs.next()) {
                loginSucces = true;
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return loginSucces;
    }


    /*
     * 初始化用户界面
     * @return用户输入的用户名和密码等登录信息
     * */
    private static Map<String, String> initeUI() {
        Scanner s = new Scanner(System.in);
        System.out.println("用户名：");
        String LoginName = s.nextLine();
        System.out.println("密码：");
        String LoginPwd = s.nextLine();
        Map<String, String> userLoginInfo = new HashMap<>();
        userLoginInfo.put("LoginName", LoginName);
        userLoginInfo.put("LoginPwd", LoginPwd);
        return userLoginInfo;
    }


}
